package com.example.chengzhengwei;

import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.chengzhengwei.utils.SpectrophotometerProtocol;

public class SelfCheckActivityV1 extends AppCompatActivity {

    private static final String TAG = "SelfCheckActivity";
    private EditText editTextSelfCheckResult, editTextReturnCode;
    private ProgressBar progressBar;
    private TextView loadingText;
    private Handler handler = new Handler();
    private AlertDialog loadingDialog;
    private SerialApp serialApp;

    // 添加回调实例
    private SerialApp.SerialReadCallback mSelfCheckReadCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_self_check);

        serialApp = (SerialApp) getApplication();

        editTextSelfCheckResult = findViewById(R.id.editTextSelfCheckResult);
        editTextReturnCode = findViewById(R.id.editTextReturnCode);

        Button buttonStart = findViewById(R.id.buttonStart);
        Button buttonBack = findViewById(R.id.buttonBack);

        progressBar = new ProgressBar(this);
        loadingText = new TextView(this);
        loadingText.setText("正在等待自检结果...");


        //======You can delete these lines that have been commented out.
        // 创建一个AlertDialog来显示加载效果
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setView(progressBar);
//        builder.setView(loadingText);
//        builder.setCancelable(false);
//        AlertDialog dialog = builder.create();
//        buttonStart.setOnClickListener(v -> {
//            editTextSelfCheckResult.setText("正在自检");
//            editTextReturnCode.setText("未知");
//            dialog.show(); // 显示加载效果
//            handler.postDelayed(() -> {
//                dialog.dismiss(); // 关闭加载效果
//                editTextSelfCheckResult.setText("自检通过");
//                editTextReturnCode.setText("63");
//            }, 3000); // 等待3秒
//        });
//        buttonBack.setOnClickListener(v -> {
//            Intent intent = new Intent(SelfCheckActivity.this, MainActivity.class);
//            startActivity(intent);
//            finish();
//        });
        //===============================================================


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("自检中");
        builder.setMessage("正在与设备通信，请稍候...");
        builder.setCancelable(false);
        loadingDialog = builder.create();

        buttonStart.setOnClickListener(v -> {
            // 清除之前的结果
            editTextSelfCheckResult.setText("");
            editTextReturnCode.setText("");

            // 显示加载对话框
            loadingDialog.show();

            //注册接受消息
            registerRecycleReading();
            // 发送自检命令
            sendSelfCheckCommand();
        });

        buttonBack.setOnClickListener(v -> {
            finish();
        });
    }

    private void sendSelfCheckCommand() {
        // 构建自检命令
        byte[] command = SpectrophotometerProtocol.buildSelfCheckCommand(
                SpectrophotometerProtocol.PC_ADDRESS
        );

        // 通过串口发送命令
        serialApp.safeWrite(command, new SerialApp.SerialWriteCallback() {
            @Override
            public void onWriteComplete(int bytesWritten) {

            }

            @Override
            public void onWriteError(Exception e) {
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    Toast.makeText(SelfCheckActivityV1.this,
                            "发送自检命令失败: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                });
            }
        });
    }

    private void handleSelfCheckResponse(byte[] data) {
        try {
            SpectrophotometerProtocol.Response response = SpectrophotometerProtocol.parseResponse(data);

            runOnUiThread(() -> {
                loadingDialog.dismiss();

                if(response.getData()==null){
                    return;
                }
                // 检查是否是自检响应
                if (response.getCommand() == SpectrophotometerProtocol.RESP_SELF_CHECK) {
                    if (response.isSelfCheckSuccessful()) {
                        editTextSelfCheckResult.setText("自检通过");
                        editTextReturnCode.setText("0x00");

                    } else {
                        editTextSelfCheckResult.setText("自检失败");

                        // 如果有返回码数据，显示第一个字节的十六进制形式
                        if (response.getData() != null && response.getData().length > 0) {
                            byte returnCode = response.getData()[0];
                            editTextReturnCode.setText(String.format("0x%02X", returnCode));
                        } else {
                            editTextReturnCode.setText("0x01"); // 默认错误码
                        }
                    }

                } else {
//                    if(response.getData()==null){
//                        Log.d(TAG,"<=收到非自检响应 null");
//                        return;
//                    }
//                    Log.d(TAG,"====>收到非自检响应:"+HexUtils.printHexV2(response.getData()));
                    // 非自检响应
                    editTextSelfCheckResult.setText("收到非自检响应");
                    editTextReturnCode.setText(String.format("0x%02X", response.getCommand()));
                    Toast.makeText(SelfCheckActivityV1.this,
                            "收到非预期响应: " + String.format("0x%02X", response.getCommand()),
                            Toast.LENGTH_LONG).show();
                }

                //不再接消息
                unregisterRecycleReading();
            });

        } catch (SpectrophotometerProtocol.ProtocolException e) {
            runOnUiThread(() -> {
                loadingDialog.dismiss();
                Toast.makeText(SelfCheckActivityV1.this,
                        "协议解析错误: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
                editTextSelfCheckResult.setText("解析错误");
                editTextReturnCode.setText("N/A");
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();


        registerRecycleReading();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 取消注册回调
        unregisterRecycleReading();
    }

    private void unregisterRecycleReading(){
        if (mSelfCheckReadCallback != null) {
            serialApp.unregisterRecycleReading(mSelfCheckReadCallback);
            mSelfCheckReadCallback = null;
        }
    }

    private void registerRecycleReading(){
        if(mSelfCheckReadCallback==null){
            // 创建并注册回调
            mSelfCheckReadCallback = new SerialApp.SerialReadCallback() {
                @Override
                public void onDataReceived(byte[] data) {
                    handleSelfCheckResponse(data);
                }
                @Override
                public void onReadError(Exception e) {
                    runOnUiThread(() -> {
                        loadingDialog.dismiss();
                        Toast.makeText(SelfCheckActivityV1.this,
                                "读取自检响应失败: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    });
                }
            };
        }
        // 注册回调
        serialApp.recycleReading(mSelfCheckReadCallback);
    }

}